<template>
  <div>
    <!-- 发件人 → 收件人（存在则显示头像+姓名） -->
    <div class="d-flex align-center mb-1 opacity-80">
      <template v-if="emailFromUser">
        <v-avatar class="mr-1 border-white" size="20">
          <v-img
            v-if="emailFromUser.avatar"
            :alt="emailFromUser.name"
            :src="emailFromUser.avatar"
          />
          <v-icon v-else :icon="mdiAccount" size="16" />
        </v-avatar>
        <span class="text-caption text-truncate">{{ emailFromUser.name }}</span>
      </template>
      <template v-else>
        <span class="text-caption text-truncate">{{ note.from }}</span>
      </template>

      <v-icon class="mx-1" :icon="mdiArrowRight" size="14" />

      <template v-if="emailToUsers && emailToUsers.length > 0">
        <template v-for="(u, idx) in emailToUsers.slice(0, 2)" :key="idx">
          <v-avatar class="mr-1 border-white" size="20">
            <v-img v-if="u.avatar" :alt="u.name" :src="u.avatar" />
            <v-icon v-else :icon="mdiAccount" size="16" />
          </v-avatar>
          <span class="text-caption mr-2 text-truncate">{{ u.name }}</span>
        </template>
        <span v-if="emailToUsers.length > 2" class="text-caption text-medium-emphasis"
          >+{{ emailToUsers.length - 2 }}</span
        >
      </template>
      <template v-else>
        <span class="text-caption text-truncate">{{ (note.to || []).join(', ') }}</span>
      </template>
    </div>

    <!-- 主题 + 附件数量 -->
    <div class="d-flex align-center mb-1 opacity-90">
      <span class="text-truncate text-h6">{{ note.subject || t('noSubject') }}</span>
      <div
        v-if="note.attachments && note.attachments.length > 0"
        class="ml-auto d-flex align-center"
      >
        <v-icon class="ml-2" :icon="mdiPaperclip" size="14" />
        <span class="text-caption ml-1">{{ note.attachments.length }}</span>
      </div>
    </div>

    <!-- 时间（发送/接收） -->
    <div class="d-flex align-center mb-1 text-caption text-medium-emphasis">
      <v-icon class="mr-1" :icon="mdiClockOutline" size="14" />
      <span>{{ formatDateTime(note.created_at) }}</span>
    </div>

    <!-- 正文两行摘要（解析特殊标记为可点击 Chip） -->
    <div class="email-snippet line-clamp-2 font-weight-regular opacity-80">
      <NoteContentRenderer
        :content="note.content"
        @click-company="handleClickCompany"
        @click-contact="handleClickContact"
        @click-user="handleClickUser"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import NoteContentRenderer from '../common/NoteContentRenderer.vue'
import { useI18n } from 'vue-i18n'
import { mdiAccount, mdiArrowRight, mdiClockOutline, mdiPaperclip } from '@mdi/js'

import type { Note, User } from '../../types'

const props = defineProps<{ note: Note }>()
const { t } = useI18n()

// 当后端未提供结构化的 from_user / to_users 时，
// 根据原始邮箱字符串生成占位的用户数据（含名称，头像留空以显示占位图标）
function extractDisplayName(address?: string): { name: string; email?: string } {
  if (!address) return { name: '' }
  const addr = address as string
  const m = addr.match(/^\s*"?([^"<]+?)"?\s*<\s*([^>]+)\s*>\s*$/)
  if (m) {
    const [, g1, g2] = m
    return { name: (g1 ?? '').trim(), email: (g2 ?? '').trim() }
  }
  const emailMatch = addr.match(/([^\s<@]+@[^\s>]+)/)
  const email = emailMatch?.[1]
  let base: string = addr
  const emailPrefix = email?.split('@')[0]
  if (emailPrefix) base = emailPrefix
  const words = base
    .replace(/["<>]/g, '')
    .split(/[._\- ]+/)
    .filter(Boolean)
  const name =
    words.length > 0
      ? words.map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')
      : email || addr
  return { name, email }
}

function fallbackUserFromAddress(address?: string, idSeed = -1): User | null {
  if (!address) return null
  const { name, email } = extractDisplayName(address)

  return { id: idSeed, name: name || email || address, email }
}

const emailFromUser = computed<User | null>(() => {
  const u = (props.note as any).from_user as User | undefined
  if (u && u.name) return u
  return fallbackUserFromAddress(props.note.from, -1)
})

const emailToUsers = computed<User[]>(() => {
  const arr = (props.note as any).to_users as User[] | undefined
  if (arr && arr.length > 0) return arr
  const tos = props.note.to || []
  return tos.map((addr, idx) => fallbackUserFromAddress(addr, -100 - idx)!)
})
// 点击 chips 事件（可由上层接管导航）
function handleClickUser(p: { id: number; name: string }) {
  console.debug('[EmailNote] click-user', p)
}

function handleClickContact(p: { contactId: number; companyId: number; name: string }) {
  console.debug('[EmailNote] click-contact', p)
}
function handleClickCompany(p: { id: number; name: string }) {
  console.debug('[EmailNote] click-company', p)
}

// 格式化日期时间（与普通笔记一致的展示）
function formatDateTime(timestamp: number): string {
  const date = new Date(timestamp)
  return date.toLocaleString()
}
</script>
<style scoped></style>

<i18n>
{
  "zhHans": {
    "noSubject": "无主题"
  },
  "en": {
    "noSubject": "No Subject"
  }
}
</i18n>
